<!-- from 7 5 2 7 1 8 9 2 0 -->
<template>
  <a-row :gutter="24">
    <a-col :md="24">
      <a-card :style="cardStyle" :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :md="4" :sm="24">
                <a-form-item label="仓库" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select
                    mode="single" :maxTagCount="1"
                    optionFilterProp="children"
                    showSearch style="width: 100%"
                    placeholder="请选择仓库"
                    v-model="depotSelected">
                    <a-select-option v-for="(depot,index) in depotList" :value="depot.id" :key="depot.id">
                      {{ depot.depotName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <a-form-item label="日期" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-date-picker placeholder="请选择日期" 
                        style="width:100%" @change="onChange"/>
                </a-form-item>
              </a-col>

              <a-col :md="6" :sm="24">
                <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="searchQuery">查询</a-button>
                  <a-button style="margin-left: 8px" @click="exportExcel" icon="download">导出</a-button>
                </span>
              </a-col>

              
            </a-row>
          </a-form>
        </div>
        <!-- table区域-begin -->
        <section ref="print" id="reportPrint">
          <a-table
            bordered
            ref="table"
            size="middle"
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :components="handleDrag(columns)"
            :pagination="false"
            :scroll="scroll"
            :loading="loading"
            @change="handleTableChange">
            <span slot="action" slot-scope="text, record">
              <a @click="showMaterialDetails(record)">流水</a>
            </span>
            <template slot="customRenderStock" slot-scope="text, record">
              <a-tooltip :title="record.bigUnitStock">
                {{text}}
              </a-tooltip>
            </template>
          </a-table>
          <a-row :gutter="24" style="margin-top: 8px;text-align:right;">
          </a-row>
        </section>
        <!-- table区域-end -->
      </a-card>
    </a-col>
    <FinanceMaterialDetailsModal ref="FinanceMaterialDetailsModal" ></FinanceMaterialDetailsModal>

  </a-row>

</template>
<script>
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { getAction } from '@/api/manage'
  import { openDownloadDialog, sheet2blob} from "@/utils/util"
  import JEllipsis from '@/components/jeecg/JEllipsis'
  import moment from 'moment'
  import Vue from 'vue'
  import FinanceMaterialDetailsModal from './modules/FinanceMaterialDetailsModal'
  export default {
    name: "FinanceDailyStockReport",
    mixins:[JeecgListMixin],
    components: {
      JEllipsis,
      FinanceMaterialDetailsModal
    },
    data () {
      return {
        // 查询条件
        labelCol: {
          span: 5
        },
        wrapperCol: {
          span: 18,
          offset: 1
        },
        queryParam: {
          depotId:'',
          reportDate:'',
        },
        depotSelected:null,
        depotList: [],
        categoryTree:[],
        totalStockStr: '0',
        totalCountMoneyStr: '0',
        // 表头
        columns: [
          {title: '', dataIndex: 'rowIndex', align:"center", width: 80,
            scopedSlots: { customRender: 'action' }
          },
          { title: '编号', dataIndex: 'materialFullBarCode', width: 100},
          // { title: '类别', dataIndex: 'materialCategoryName', width: 100},
          { title: '名称', dataIndex: 'material.name', width: 100},
          {title: '单位', dataIndex: 'material.unit', width: 60},
          { title: '初始化库存', dataIndex: 'initialStock', width: 100,type:'number'},
          { title: '默认库存', dataIndex: 'currentStock', width: 100,type:'number'},
          { title: '先进先出库存', width: 80, dataIndex: 'count',type:'number'},
          { title: '单价', width: 80, dataIndex: 'price', },
          { title: '合计', dataIndex: 'subTotal', width: 100,type:'number'},
          { title: '最新采购单价', dataIndex: 'purchaseDecimal', width: 100,type:'number'},
          { title: '制造商', dataIndex: 'material.mfrs', width: 100},
          { title: '规格型号', dataIndex: 'material.model', width: 100},
          { title: '材质', dataIndex: 'material.caizhi', width: 100},
          { title: '标准', dataIndex: 'material.biaozhun', width: 100},
          { title: '尺寸', dataIndex: 'material.otherField1', width: 100},
          { title: '抛光要求', dataIndex: 'material.paoguangdu', width: 100},
          { title: '连接形式', dataIndex: 'material.lianjie', width: 100},
          { title: '温度', dataIndex: 'material.otherField2', width: 100},
          { title: '压力', dataIndex: 'material.otherField3', width: 100},
          { title: '密封要求', dataIndex: 'material.mopian', width: 100},
          { title: '长度', dataIndex: 'material.changdu', width: 100},
          // { title: '其他技术参数', dataIndex: 'material.standard', width: 100}
        ],
        url: {
          list: "/finance-report/daily-report",
          totalCountMoney: "/depotItem/totalCountMoney",
          exportXlsUrl: "/depotItem/exportExcel"
        }
      }
    },
    created() {
      this.getDepotData()
    },
    mounted () {
      this.scroll.x = 1620
    },
    methods: {
      moment,
      getQueryParams() {
        let param = Object.assign({}, this.queryParam, this.isorter);
        param.depotId = this.depotSelected;
        param.reportDate = this.queryParam.reportDate;
        return param;
      },
      getDepotData() {
        getAction('/depot/findDepotByCurrentUser').then((res)=>{
          if(res.code === 200){
            this.depotList = res.data;
          }else{
            this.$message.info(res.data);
          }
        })
      },
      getDepotName(id){
        for(let i = 0; i < this.depotList.length; i++){
          if(this.depotList[i].id == id){
            return this.depotList[i].depotName;
          }
        }
      },
      onChange: function (value, dateString) {
        this.queryParam.reportDate=dateString;
      },
      onDepotChange: function (value) {
        console.log(value);
        this.queryParam.id = value;
      },
      searchQuery() {
        console.log(this.queryParam.reportDate,this.depotSelected);
        if(this.queryParam.reportDate != '' && this.depotSelected != '' ){
          this.loadData(1);
        } else {
          this.$message.warning('请选择日期和仓库！')
        }
      },
      showMaterialDetails(record){
        this.$refs.FinanceMaterialDetailsModal.edit(record);
        this.$refs.FinanceMaterialDetailsModal.title = "查看材料库存流水_"+record.material.name+"_"+this.getDepotName(this.depotSelected)  ;
        this.$refs.FinanceMaterialDetailsModal.disableSubmit = false;
      },
      exportExcel() {
        // 根据columns数组动态生成表头
        let headers = []
        for (let i = 0; i < this.columns.length; i++) {
          let col = this.columns[i]
          // 跳过第一列（行号列），因为它没有实际的业务数据
          if (col.dataIndex === 'rowIndex') {
            continue
          }
          headers.push(col.title)
        }
        
        let aoa = [headers]
        
        // 遍历数据源，为每一行生成对应的数据数组
        for (let i = 0; i < this.dataSource.length; i++) {
          let ds = this.dataSource[i]
          let item = []
          
          // 根据columns数组的dataIndex动态获取数据
          for (let j = 0; j < this.columns.length; j++) {
            let col = this.columns[j]
            // 跳过行号列
            if (col.dataIndex === 'rowIndex') {
              continue
            }
            
            // 处理嵌套对象属性（如 material.name）
            let value = this.getNestedValue(ds, col.dataIndex)
            item.push(value)
          }
          
          aoa.push(item)
        }
        
        openDownloadDialog(sheet2blob(aoa), '库存统计_'+this.queryParam.reportDate+'_'+this.getDepotName(this.depotSelected))
      },
      
      // 辅助函数：获取嵌套对象属性的值
      getNestedValue(obj, path) {
        if (!path) return ''
        
        // 处理嵌套属性，如 'material.name'
        if (path.includes('.')) {
          let keys = path.split('.')
          let value = obj
          for (let key of keys) {
            if (value && typeof value === 'object' && key in value) {
              value = value[key]
            } else {
              value = ''
              break
            }
          }
          return value || ''
        } else {
          return obj[path] || ''
        }
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less'
</style>